package com.wx.mp.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wx.mp.utils.BizResultVO;
import com.wx.mp.utils.ErrorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory.getLogger(AdminLoginInterceptor.class);

    private static final String MIME_JSON = "application/json;charset=UTF-8";

    //在请求进入controller前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        String host = request.getHeader("Host");
        String url = request.getRequestURI();
        if(session == null || session.getAttribute("userInfo")==null){
            log.info("请求地址："+url+"不允许，请先登陆");
            PrintWriter writer = response.getWriter();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", MIME_JSON);
            response.setContentType(MIME_JSON);
            BizResultVO<?> bizResultVO = new BizResultVO<>(ErrorType.AUTH_TOKEN_NOT_EXISTS,"请先登陆");
            response.setStatus(HttpStatus.OK.value());
            writer.write(JSONObject.toJSON(bizResultVO).toString());
            writer.close();
            return false;

        }else{
            return true;
        }
    }
}
